<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="240px" class="tree_css">
        <h3>组织机构列表</h3>
        <FITree
          :key="treeKey"
          ref="treeDataRef"
          class="tree_box"
          :treeList="treeList"
          :filter-node-method="filterNode"
          :showFilter="true"
          :showCheckbox="false"
          @nodeClick="nodeClick"
          :draggable="true"
        ></FITree>
      </el-aside>
      <el-container>
        <el-main>
          <FISearchForm
            ref="ruleFormRef"
            :id="`inqu_${tableId}`"
            :searchNum="getHasSearchValues(state.query)"
            v-model:form-value="state.query"
            :table-column="columns"
            :wrapperSpan="searchWrapperSpan"
            @submit="searchFn"
          >
            <el-col :span="searchWrapperSpan" class="flex-center">
              <FIFormItem prop="orgEname" label="组织机构编码">
                <FIInput v-model="state.query.orgEname" clearable />
              </FIFormItem>
            </el-col>
            <el-col :span="searchWrapperSpan" class="flex-center">
              <FIFormItem prop="orgCname" label="组织机构名称">
                <FIInput v-model="state.query.orgCname" clearable />
              </FIFormItem>
            </el-col>
            <el-col :span="searchWrapperSpan" class="flex-center">
              <FIFormItem prop="orgType" label="组织类型">
                <!-- <FIInput v-model="state.query.orgType" clearable /> -->
                <FISelect
                  v-model="state.query.orgType"
                  valueCustom="value"
                  :options="[
                    { value: 'company', label: '公司' },
                    { value: 'dept', label: '部门' },
                  ]"
                  clearable
                />
              </FIFormItem>
            </el-col>
            <el-col :span="searchWrapperSpan" class="flex-center">
              <FIFormItem name="status" label="状态">
                <FISelect
                  v-model="state.query.status"
                  valueCustom="value"
                  :options="[
                    { value: '1', label: '开启' },
                    { value: '0', label: '关闭' },
                  ]"
                  clearable
                />
              </FIFormItem>
            </el-col>
          </FISearchForm>
          <div class="margin-bottom20"></div>
          <FITable
            ref="tableRef"
            class="box-radius2"
            title="组织机构列表"
            :id="`result_${tableId}`"
            :readonly="false"
            :data="state.dataList"
            primaryKey="orgId"
            v-model:columns="columns"
            :isLoading="isTableLoading"
            insertable
            deletable
            :saveSuccessful="saveSuccessful"
            :pageConfig="pageConfig"
            @row-add-save="addRowSave"
            @table-refresh="searchFn"
            @selection-change="handleSelectionChange"
            @size-change="handleSizeChange"
            @current-page-change="handleCurrentChange"
            @row-delete="deleteRow"
          >
            <template #headerBtn>
              <!-- <FIPopconfirmBtn
                title="您是否确认删除选中数据吗？"
                buttonText="删除"
                beforePopText="请选择一条数据"
                :btn-binds="{ id: 'delete', border: true }"
                :isVisible="!!checkedRows.length"
                @confirm="deleteRow"
              >
              </FIPopconfirmBtn> -->
            </template>
          </FITable>
        </el-main>
      </el-container>
    </el-container>

    <FIModel v-model="orgVisible" width="500" title="变更组织机构" @confirm="orgConfirm">
      <FIFormItem name="isAuth" label="所属组织机构">
        <FICascader @select-data="selectData"></FICascader>
      </FIFormItem>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, toRaw, defineEmits } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import FIForm from '@/components/FIForm.vue'
import FIModal from '@/components/FIModal.vue'
import FICascader from '@/components/FICascader.vue'
import FITree from '@/components/FITree.vue'
import { apiDeptMaintquery, apiGetDeptTree, apialterDept, apiDeptMaintdelete, apiDeptMaintsave } from '@/api/user'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData, getHasSearchValues } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const emits = defineEmits(['get-tree-list'])
const route = useRoute()
const defaultProps = {
  children: 'subNodes',
  // label: 'payload.orgCname',
  label: (data) => data.payload.orgCname,
}
const searchWrapperSpan = 8
const showSearch = ref(true)
const orgVisible = ref(false)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'orgManage'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const treeDataRef = ref()
const modelValue = ref(false)
const treeList = ref([])
const treeKey = ref(0)
const rawArray = ref([])
const parentOrgId = ref('')
const isUpdate = ref(false) //是否更新
const orgSelect = reactive({
  label: '',
  value: '',
})
const state = reactive({
  query: {
    current: 1,
    size: 10,
    orgEname: '',
    orgCname: '',
    orgType: '',
    status: '',
  },
  dataList: [],
})
const registerRules = reactive({})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const columns: Column[] = reactive([
  {
    label: '组织机构编码',
    prop: 'orgEname',
    align: 'center',
    queryName: '',
    editable: true,
    filterable: false,
    readonly: true,
    required: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { orgEname: [{ required: true, message: '请输入组织机构编码', trigger: 'blur' }] },
    },
  },
  {
    label: '组织机构名称',
    prop: 'orgCname',
    align: 'center',
    queryName: '',
    editable: true,
    filterable: false,
    required: true,
    readonly: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { orgCname: [{ required: true, message: '请输入组织机构名称', trigger: 'blur' }] },
    },
  },
  {
    label: '组织类型',
    prop: 'orgType',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    editType: 'select',
    editable: true,
    filterable: false,
    required: true,
    sortable: false,
    sortValue: '',
    editConfig: {
      rules: { orgType: [{ required: true, message: '请选择组织类型', trigger: 'change' }] },
      options: [
        { value: 'company', label: '公司' },
        { value: 'dept', label: '部门' },
      ],

      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '状态',
    prop: 'status',
    align: 'center',
    queryName: '',
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    filterable: false,
    required: true,
    modelValue: [],
    sortable: false,
    sortValue: '',
    editConfig: {
      rules: { status: [{ required: true, message: '请选择状态', trigger: 'change' }] },
      options: [
        { value: '1', label: '开启' },
        { value: '0', label: '关闭' },
      ],
    },
  },

  {
    label: '排序',
    prop: 'sortIndex',
    align: 'center',
    editable: true,
    filterable: false,
    sortable: false,
    modelValue: { inputValue: '' },
    editType: 'input',
  },
  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const nodeClick = (val) => {
  parentOrgId.value = val.value
  // state.query.orgEname = val.orgEname
  // state.query.orgCname = val.label
  searchFn('query', '', val.value)
}
const selectData = (val, name) => {
  orgSelect.label = name
  orgSelect.value = val
}
//删除事件
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.orgId) ids.push(item?.orgId)
    })
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('delete', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        // searchFn('query','',parentOrgId.value)
        getTreeList(parentOrgId.value)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // useMessage().error(error.message)
    })
}
const orgConfirm = () => {
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.userId) ids.push(item?.userId)
    })

  isTableLoading.value = true
  const par = {
    deptId: orgSelect.value,
    userIds: ids,
  }
  apialterDept(par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        orgVisible.value = false
        searchFn()
      }
    })
    .catch((error: any) => {
      useMessage().error(error.data.message)
      isTableLoading.value = false
    })
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any, orgId?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const par = {
    parentOrgId: orgId || parentOrgId.value,
    ...state.query,
  }
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  for (let i of checkedRows.value) {
    i['parentOrgId'] = parentOrgId.value
  }
  const apiUrl = proxy.$Button_api('save', route.name)
  apiRequestPost(apiUrl, checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        useMessage().success(res.data.message)
        // emits('get-tree-list')
        // treeDataRef.value.getTreeList()
        // tableRef.value.clearSelection()
        getTreeList(parentOrgId.value)
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  if (!parentOrgId.value) {
    useMessage().warning('请选择组织机构部门')
    return
  }
  handleSave()
}
const getTreeList = async (id) => {
  const { data } = await apiGetDeptTree()
  if (data.success) {
    treeList.value = data.data.subNodes
    treeKey.value += 1
    // searchFn('query', '', id ? id : data.data.nodeNo)
  }
}

//   const apiFunc = async(apiUrl) =>{
// 	const {data} = await apiUrl({loginName:toRaw(checkedRows.value[0]).loginName})
// 	if(data.success){
// 		useMessage().success(data.message)
// 		searchFn()
// 	}
//   }
watch(
  () => columns,
  (newValue) => {},
  { deep: true, immediate: true } // 开启深度监听，因为数组或对象内部属性的改变浅层监听可能无法捕获
)
onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns

  getTreeList()
})
</script>
<style lang="less" scoped>
@import '~@/assets/style/common.less';
/deep/ .el-main {
  padding-top: 0;
}
.tree_css {
  height: 100%;
  background: #ffffff;
  // padding:10px;
  height: calc(100vh - 200px);
  .tree_box {
    padding: 0 12px;
  }
  h3 {
    font-size: 18px;
    line-height: 55px;
    padding-left: 15px;
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
    color: #000000;
  }
}
</style>
